<?php
/**
 * @Author:      lyt
 * @DateTime:    2015-12-28 15:32:48
 * @Description: 用于 scs 系统用户的登录登出
 */
class ScsUserController extends BaseController {

    /**
     * @Author:      lyt
     * @DateTime:    2016-03-29 11:10:11
     * @Description: 验证token 
     */
    public  function checkToken(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');

        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "checkToken", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /*
     * 技师登陆
     * 
     */
    public function login(){
        $validator = Validator::make(Input::all(),
            array(
                'username' => 'required',
                'passwd' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_args_error_21001");
                break;
            }

            //传入参数
            $username = Input::get('username');
            $passwd = SCUser::make(Input::get('passwd'));

            //验证密码
            $sc_user=SCUser::findUserByUP($username,$passwd);

            if(!is_null($sc_user)){
                if($sc_user->status!=1){
                    $response = Lang::get("scs_error.login_user_status_error_21002");
                    break;
                }
                $ms=MaintenanceShops::find($sc_user->shop_id);
                if(is_null($ms)){
                    $response = Lang::get("scs_error.scs_user_shop_error_21013");
                    break;
                }
                if($ms->status!=1){
                    $response = Lang::get("scs_error.scs_user_shop_status_error_21014");
                    break;
                }
                $print_name=empty($ms->print_title) ? "北京安惠汽车服务有限公司".$ms->name : $ms->print_title;
                //删除 scs 用户 token

                if (strtotime($sc_user->pwd_at) + $ms->password_day*24*60*60 <= time()) {  //当前时间是不是超过了门店用户的有效登陆时间
                    $response = Lang::get("scs_error.scs_user_login_error_21017");
                    break;
                }
                
                try {
                    $sc_user->login_num = $sc_user->login_num + 1;
                    $sc_user->save();
                    
                    ScsUserToken::where('sc_user_id',$sc_user->id)->delete();
                    $sc_token = new ScsUserToken;
                    $sc_token->sc_user_id = $sc_user->id;
                    $sc_token->token = md5($username.time().rand(0,100));
                    $sc_token->created_at = Common::num2DateTime(time());
                    $sc_token->out_time_at = Common::num2DateTime(time() + Config::get("scs_user.token_time_out"));
                    $sc_token->save();
                } catch (Exception $e) {
                    Log::error("error", array("system" => "scs" ,"event" => "login", 'input' =>Input::all() ,"exception" => $e));
                    $response = Lang::get("scs_error.login_create_token_error_21004");
                    break;
                }
            }else{
                $response = Lang::get("scs_error.login_user_userpw_error_21003");
                break;
            }
            
            //查看打当天是否有提醒
            $start_date = date("Y-m-d 00:00:00");
            $end_date = date("Y-m-d 23:59:59");
            $info = Remind::where("shop_id",$sc_user->shop_id)
                    ->where("remind_at",">",$start_date)
                    ->where("remind_at","<",$end_date)
                    ->where("status",1)
                    ->get();
            $is_remind = !empty($info->toarray()) ? 1 : 0; 
            
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array(
                    'id' => $sc_user->id,
                    'name' => $sc_user->real_name,
                    'title' => $sc_user->title,
                    'token' => $sc_token->token,
                    'expired' => $sc_token->out_time_at,
                    'shop_id' =>$ms->id,
                    'shop_name'=>$ms->name,
                    'shop_address' =>$ms->address,
                    'shop_desc'=>$ms->desc,
                    'business_is_enabled'=>$ms->business_is_enabled,
                    'print_name'=>$print_name,
                    'is_remind' => $is_remind
                )
            );
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2015-12-28 19:04:14
     * @Description: scs 用户登出
     */
    public function logout(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }
            try{
                ScsUserToken::where('sc_user_id',$sc_user->id)->delete();
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "logout", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("scs_error.user_token_clean_error_21007");
                break;
            }
            //组织返回
            $response = array(
                'code' => 0,
                'msg' => 'ok',
                'result' => array()
            );
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "logout", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:    2016-03-15 11:16:37
     * @Description: 用于查看 sc用户的信息
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){                
                break;
            }
            $sc=SCUser::where("shop_id",$sc_user->shop_id)->where("status",1)->select("id","user_name","real_name")->get();            
            //组织返回
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>sizeof($sc),"user"=>$sc));
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "lists", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    
    /*
     * 修改密码
     *
     */
    public function modifyPwd(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'passwd' => 'required|regex:/^[1-9]{3,9}$/',
                'old_passwd' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages();
                break;
            }
            $old_passwd=md5(Input::get('old_passwd'));
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(!is_null($sc_user)){
                
                if($sc_user->password != $old_passwd && $sc_user->password != strtoupper($old_passwd)){
                    $response = Lang::get("scs_error.user_passwd_error_21015");
                    break;
                }
                if($sc_user->status!=1){
                    $response = Lang::get("scs_error.login_user_status_error_21002");
                    break;
                }
                $sc=SCUser::find($sc_user->id);
                $sc->password=strtoupper(md5(Input::get('passwd')));
                $sc->updated_at=date("Y-m-d H:i:s");
                $sc->pwd_at=date("Y-m-d H:i:s");
                $sc->save();
                
            }else{
                $response = Lang::get("scs_error.scs_user_not_exiet21009");
                break;
            }
    
            try{
                ScsUserToken::where('sc_user_id',$sc_user->id)->delete();
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "logout", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("scs_error.user_token_clean_error_21007");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * 修改密码
     *
     */
    public function modifyPwd2(){
        $validator = Validator::make(Input::all(),
            array(
                'user_name' => 'required',
                'passwd' => 'required',
                'old_passwd' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages();
                break;
            }
            $user_name = Input::get('user_name');
            $old_passwd = md5(Input::get('old_passwd'));
            $user = SCUser::where("user_name",$user_name)->where('password',$old_passwd)
                    ->select("id","user_name","status")
                    ->first();

            if(!isset($user->id)){
                $response = Lang::get("scs_error.login_user_userpw_error_21003");
                break;
            }
            
            if($user->status!=1){
                $response = Lang::get("scs_error.login_user_status_error_21002");
                break;
            }
            
            $sc=SCUser::find($user->id);
            $sc->password=strtoupper(md5(Input::get('passwd')));
            $sc->updated_at=date("Y-m-d H:i:s");
            $sc->pwd_at=date("Y-m-d H:i:s");
            $sc->save();

            try{
                ScsUserToken::where('sc_user_id',$user->id)->delete();
            } catch (Exception $e) {
                Log::error("error", array("system" => "scs" ,"event" => "logout", 'input' =>Input::all() ,"exception" => $e));
                $response = Lang::get("scs_error.user_token_clean_error_21007");
                break;
            }
             $response = array('code' => 0, 'msg' => 'ok', 'result' => $sc->id);
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /*
     * 判断是否是第一次登陆
     *
     */
    public function first_login(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages();
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok');
            $token = Input::get('token');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(empty($sc_user)){
                $response = Lang::get("scs_error.args_error_10000");
                break;
            }
             $response = array('code' => 0, 'msg' => 'ok', 'result' => $sc_user->login_num);
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
     /*
     * 
     *增加一次登陆次数
     */
    public function add_login_num(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages();
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok');
            $token = Input::get('token');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            
            $sc=SCUser::find($sc_user->id);
            $sc->login_num = $sc_user->login_num + 1;
            $result = $sc->save();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"event" => "login", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

}